﻿namespace instamuz.Infrastructure
{
    using Castle.Core;
    using Castle.Facilities.TypedFactory;
    using Castle.MicroKernel;
    using Castle.MicroKernel.Registration;
    using Castle.MicroKernel.SubSystems.Configuration;
    using Castle.Windsor;
    using DataAccess;
    using IndyCode.Infrastructure.Domain;
    using IndyCode.Infrastructure.NHibernate;
    using JetBrains.Annotations;
    using NHibernate;

    [UsedImplicitly]
    public class NHibernateInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.AddFacility<TypedFactoryFacility>();

            container.Register(
                Component.For<ISessionProvider>().ImplementedBy<SessionProvider>(),
                Component.For<IUnitOfWorkFactory>().ImplementedBy<NHibernateUnitOfWorkFactory>(),
                Component.For<INHibernateInitializer>().ImplementedBy<NHibernateInitializer>(),
                Component.For<ILinqProvider>().ImplementedBy<NHibernateLinqProvider>(),
                Component.For<ISessionFactory>().UsingFactoryMethod(BuildSessionFactory)
                    .LifeStyle.Is(LifestyleType.Singleton));
        }

        private static ISessionFactory BuildSessionFactory(IKernel x)
        {
            return x.Resolve<INHibernateInitializer>().GetConfiguration().BuildSessionFactory();
        }
    }
}